//
//  DeviceManager.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/13.
//

import UTEBluetoothRYApi

class DeviceManager: ObservableObject {
    static let shared = DeviceManager()
    private let devicesKey = "SavedDevices"
    private let lastDeviceKey = "LastConnectedDevice"
    @Published var devices: [DeviceInfo] = []
    @Published var lastConnectedDevice: DeviceInfo?
    var uteDevices: [UTEModelDevice] {
        return devices.map { $0.toUTEModelDevice() }
    }
    private init() {
        loadDevices()
        loadLastDevice()
    }
    
    // MARK: - 设备列表管理
    func addOrUpdateDevice(_ device: DeviceInfo) {
        if let index = devices.firstIndex(where: { $0.identifier == device.identifier }) {
            devices[index] = device
        } else {
            devices.append(device)
        }
        saveDevices()
    }
    
    func removeDevice(id: String) {
        devices.removeAll { $0.identifier == id }
        saveDevices()
        
        // 如果删除的是最后连接设备，则清空记录
        if lastConnectedDevice?.identifier == id {
            lastConnectedDevice = nil
            saveLastDevice()
        }
    }
    
    // MARK: - 最后连接设备管理
    func setLastConnectedDevice(_ device: DeviceInfo) {
        let updatedDevice = device
        lastConnectedDevice = updatedDevice
        
        // 同时更新设备列表中的记录
        addOrUpdateDevice(updatedDevice)
        saveLastDevice()
    }
    
    // MARK: - 持久化存储
    private func saveDevices() {
        do {
            let data = try JSONEncoder().encode(devices)
            UserDefaults.standard.set(data, forKey: devicesKey)
        } catch {
            print("保存设备列表失败: \(error)")
        }
    }
    
    private func loadDevices() {
        guard let data = UserDefaults.standard.data(forKey: devicesKey) else { return }
        do {
            devices = try JSONDecoder().decode([DeviceInfo].self, from: data)
        } catch {
            print("加载设备列表失败: \(error)")
        }
    }
    
    private func saveLastDevice() {
        guard let device = lastConnectedDevice else {
            UserDefaults.standard.removeObject(forKey: lastDeviceKey)
            return
        }
        
        do {
            let data = try JSONEncoder().encode(device)
            UserDefaults.standard.set(data, forKey: lastDeviceKey)
        } catch {
            print("保存最后设备失败: \(error)")
        }
    }
    
    private func loadLastDevice() {
        guard let data = UserDefaults.standard.data(forKey: lastDeviceKey) else { return }
        do {
            lastConnectedDevice = try JSONDecoder().decode(DeviceInfo.self, from: data)
        } catch {
            print("加载最后设备失败: \(error)")
        }
    }
}
